package com.cah.game;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cah.library.UserFunctions;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class PendingGameFragment extends Fragment
{
	private String gameName, gameKey, userKey;
	Button startButton, cancelButton, joinButton, leaveButton;
	LinearLayout playerList;
	MainActivity main;
	JSONObject pendingInfo;
	
	public PendingGameFragment(String gameKey)
	{
		super();
		this.gameKey = gameKey;
	}
	
	public PendingGameFragment()
	{
		super();
		this.gameKey = "";
	}
	
	public void onSaveInstanceState(Bundle outState)
	{
		outState.putString("gameKey", gameKey);
		outState.putString("pendingInfo", pendingInfo.toString());
	}
	
	
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		
		if(savedInstanceState != null)
		{
			gameKey = savedInstanceState.getString("gameKey");
			try
			{
				pendingInfo = new JSONObject(savedInstanceState.getString("pendingInfo"));
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}
		
		main = (MainActivity)getActivity();
		main.actionBar.setDisplayHomeAsUpEnabled(true);
		main.historyBackVisible = false;
		main.historyForwardVisible = false;
		main.invalidateOptionsMenu();
		userKey = main.getUserKey();
		
		playerList = (LinearLayout)main.findViewById(R.id.pendingGamePlayersLinearLayout);
		startButton = (Button)main.findViewById(R.id.startGameButton);
		cancelButton = (Button)main.findViewById(R.id.cancelGameButton);
		joinButton = (Button)main.findViewById(R.id.joinGameButton);
		leaveButton = (Button)main.findViewById(R.id.leaveGameButton);
		
		if(savedInstanceState != null)
		{
			setPendingInfo();
		}
		else
		{
			new PendingInfoProcess().execute();
		}
		
			
		joinButton.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View arg0)
			{
				new JoinProcess().execute();
				
			}
		});
		
		leaveButton.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View arg0)
			{
				new LeaveProcess().execute();
				
			}
		});
		
		startButton.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View arg0)
			{
				new StartProcess().execute();
				
			}
		});
		
		cancelButton.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View arg0)
			{
				new CancelProcess().execute();
			}
		});
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.game_pending, container, false);
	}
	
	private class PendingInfoProcess extends AsyncTask<Void, Void, JSONObject>
	{
		ProgressDialog pdia;
		@Override
		protected void onPreExecute()
		{
			pdia = new ProgressDialog(main);
			pdia.setMessage("Loading your game...");
			pdia.show();
		}
		
		@Override
		protected JSONObject doInBackground(Void... params)
		{
			UserFunctions uf = new UserFunctions(userKey);
			return uf.fetchPendingGameInfo(gameKey);
		}
		
		protected void onPostExecute(JSONObject json)
		{
			pendingInfo = json;
			setPendingInfo();
			pdia.dismiss();
		}
		
	}
	
	private void setPendingInfo()
	{
		try
		{
			if(pendingInfo.getInt("success")==1)
			{
				JSONObject value = pendingInfo.getJSONObject("value");
				String hostKey = value.getString("hostKey");
				int maxPlayers = value.getInt("maxPlayers");
				gameName = value.getString("gameName");
				main.setTitle(gameName);
				
				JSONArray players = value.getJSONArray("players");
				int spaces = maxPlayers - players.length();
				boolean isInGame = false;
				boolean isFull = (spaces==0);
				boolean isHost = (hostKey.equals(userKey));
				
				for(int i=0;i<players.length();i++)
				{
					JSONObject playerJson = players.getJSONObject(i);
					String playerKey = playerJson.getString("playerKey");
					String playerName = playerJson.getString("playerName");
					
					if(playerKey.equals(userKey))
					{
						isInGame = true;
					}
											
					TextView playerTextView = new TextView(main);
					playerTextView.setText(playerName);
					playerList.addView(playerTextView);
				}
				
				if(isFull)
				{
					joinButton.setEnabled(false);
				}
				else
				{
					startButton.setEnabled(false);
				}
				
				if(isInGame)
				{
					joinButton.setEnabled(false);
				}
				else
				{
					leaveButton.setEnabled(false);
				}
				
				if(isHost)
				{
					leaveButton.setEnabled(false);
					
				}
				else
				{
					startButton.setEnabled(false);
					cancelButton.setEnabled(false);
				}
				
			}
			else
			{
				Toast.makeText(main, "Something went wrong!", Toast.LENGTH_SHORT).show();
			}
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
	}
	
	private class JoinProcess extends AsyncTask<Void, Void, JSONObject>
	{
		ProgressDialog pdia;
		@Override
		protected void onPreExecute()
		{
			pdia = new ProgressDialog(main);
			pdia.setMessage("Joining game...");
			pdia.show();
		}
		
		@Override
		protected JSONObject doInBackground(Void... params)
		{
			UserFunctions uf = new UserFunctions(userKey);
			return uf.addPlayerToGame(userKey, gameKey);
		}
		
		protected void onPostExecute(JSONObject json)
		{
			try
			{
				if(json.getInt("success")==1)
				{
					main.startPendingGameFragment(gameKey);
				}
				else
				{
					Toast.makeText(main, "Something went wrong!", Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
			pdia.dismiss();
		}
		
	}
	
	private class LeaveProcess extends AsyncTask<Void, Void, JSONObject>
	{
		ProgressDialog pdia;
		@Override
		protected void onPreExecute()
		{
			pdia = new ProgressDialog(main);
			pdia.setMessage("Leaving game...");
			pdia.show();
		}
		
		@Override
		protected JSONObject doInBackground(Void... params)
		{
			UserFunctions uf = new UserFunctions(userKey);
			return uf.removePlayerFromGame(userKey, gameKey);
		}
		
		protected void onPostExecute(JSONObject json)
		{
			try
			{
				if(json.getInt("success")==1)
				{
					main.startPendingGameFragment(gameKey);
				}
				else
				{
					Toast.makeText(main, "Something went wrong!", Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
			pdia.dismiss();
		}
		
	}
	
	private class CancelProcess extends AsyncTask<Void, Void, JSONObject>
	{
		ProgressDialog pdia;
		@Override
		protected void onPreExecute()
		{
			pdia = new ProgressDialog(main);
			pdia.setMessage("Canceling game...");
			pdia.show();
		}
		
		@Override
		protected JSONObject doInBackground(Void... params)
		{
			UserFunctions uf = new UserFunctions(userKey);
			return uf.cancelGame(gameKey);
		}
		
		protected void onPostExecute(JSONObject json)
		{
			try
			{
				if(json.getInt("success")==1)
				{
					main.startPendingGameListFragment();
				}
				else
				{
					Toast.makeText(main, "Something went wrong!", Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
			pdia.dismiss();
		}
		
	}
	
	private class StartProcess extends AsyncTask<Void, Void, JSONObject>
	{
		ProgressDialog pdia;
		@Override
		protected void onPreExecute()
		{
			pdia = new ProgressDialog(main);
			pdia.setMessage("Starting game...");
			pdia.show();
		}
		
		@Override
		protected JSONObject doInBackground(Void... params)
		{
			UserFunctions uf = new UserFunctions(userKey);
			return uf.startGame(gameKey);
		}
		
		protected void onPostExecute(JSONObject json)
		{
			try
			{
				if(json.getInt("success")==1)
				{
					main.startGameFragment(gameKey, 1);
				}
				else
				{
					Toast.makeText(main, "Something went wrong!", Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
			pdia.dismiss();
		}
		
	}
}
